package com.ctgu.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.project.entity.UsersEntity;
import com.ctgu.project.mapper.UsersMapper;
import com.ctgu.project.service.UsersService;
import com.ctgu.project.utils.ApiResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
* @author Alex2
* @description 针对表【t_users】的数据库操作Service实现
* @createDate 2025-02-25 10:48:11
*/
@Log4j2
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersEntity>
    implements UsersService {

    private final String TAG = "Alex";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ApiResult sign(Integer userId) {
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        //获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth() - 1;
        redisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        return ApiResult.success("签到成功");
    }

    @Override
    public ApiResult getSignCount(Integer userId) {
        // 获取日期
        LocalDateTime now = LocalDateTime.now();
        String key = "sign:" + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字
        List<Long> result = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(
                BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()) {
            return ApiResult.error("没有签到");
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return ApiResult.error("没有签到");
        }
        Integer count = transformInteger2Binary(num);
        return ApiResult.success("获取连续签到天数成功", count);
    }

    public Integer transformInteger2Binary(Long num) {
        int count = 0;
        while ((num & 1) != 0) {
            count++;    //让该数字与1做与运算，得到数字的最后一个bit位，该bit位是否不为0则代表当天签到了
            num >>>= 1; //把数字右移一位，抛弃最后一个bit位，继续下一个bit位
        }
        return count;
    }
}